import {
    createRouter,
    createWebHistory
} from "vue-router";
import HomeView from "../views/HomeView.vue";
import {
    getToken,
    setToken,
    removeToken
} from "@/utils/token";
import {
    userStore
} from "@/stores/user";
import {
    getUserinfo
} from "@/api/user";

const router = createRouter({
    history: createWebHistory(
        import.meta.env.BASE_URL),
    routes: [{
            path: "/",
            component: () => import("@/layout/index.vue"),
            redirect: "/dashboard",
            children: [{
                    path: "/dashboard",
                    name: "dashboard",
                    component: () => import("@/views/DashboardView.vue"),
                },
                {
                    path: "/category",
                    name: "category",
                    component: () => import("@/views/CategoryView.vue"),
                },
                {
                    path: "/about",
                    name: "about",
                    component: () => import("@/views/AboutView.vue"),
                },
            ],
        },

        //登录路由
        {
            path: "/login",
            name: "login",
            component: () => import("@/views/LoginView.vue"),
            meta: {
                title: "管理员登录",
            },
        },

        // 404页面
        {
            path: "/:pathMatch(.*)*",
            name: "not-found",
            component: () => import("../views/NotFoundView.vue"),
            meta: {
                title: "页面未找到",
            },
        },
    ],
});

const pageTitle = "陕西华氏内容管理系统"
const whiteList = ["login", "not-found"]
router.beforeEach(async (to, from, next) => {
    console.log("to:", to);
    console.log("from:", from);
    if (to.meta.title) {
        document.title = to.meta.title + " - " + pageTitle
    } else {
        document.title = pageTitle
    }
    const token = getToken()
    if (!token) {
        if (whiteList.indexOf(to.name) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
        }
    } else {
        if (to.name == "login") {
            next(`/`)
        } else {
            // 读取用户信息
            //pinia
            const store = userStore()
            if (!store.userName) {
                next()
            } else {
                let res = await getUserinfo()
                console.log('res: ', res);
                if (res.code == 1) {
                    setToken(res.data.token)
                    store.setUserinfo(res.data)
                    next()
                } else {
                    removeToken()
                    store.resetUserinfo()
                    next(`/login?redirect=${to.path}`)
                }
            }
        }
    }
});
export default router;